package com.demo.config;

import com.demo.formatter.MyFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.PostConstruct;

@Configuration//表示这是一个配置类
@EnableWebMvc//开启对SpringMVC的支持
@ComponentScan(basePackages = {"com.demo.controller", "com.demo.formatter"})//扫描的基本包
public class SpringMVCConfig implements WebMvcConfigurer {

    /**
     * 用于注册格式化转换器
     */
    @Autowired
    private FormattingConversionService formattingConversionService;

    @Autowired
    private MyFormatter myFormatter;

    /**
     * 配置视图解析器
     *
     * @return
     */
    @Bean
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }


    /**
     * 注册格式化转换器
     */
    /**
     *  @PostConstruct 修饰的方法 会在服务器加载Servlet的时候运行，并且只会被服务器调用一次
     *  类似于Servlet中的init方法
     *  @PostConstruct 修饰的方法会在构造函数之后，init方法之前运行
     */
    @PostConstruct
    public void initEditableAvlidation() {
        if (formattingConversionService != null) {
            formattingConversionService.addFormatter(myFormatter);
        }
    }
}
